
local s_util = require "libs/settingmanager"
local e_util = require "libs/entutil"
local t_util = require "libs/tableutil"
local s_data = s_util:GetSettingLine("screendata")
local screen_data = {}
-- overlays 屏幕光晕 snowtile 地面积雪 sandover 沙暴 pauseover 暂停
-- leafcanopy 华盖 light_rays 天光 oceanvine_deco 藤蔓
-- helmover 装备 woodieover 伍迪滤镜 map_bg 地图半透明
-- 泰拉浆果 terr_berry
local function GetHUD()
    return GLOBAL.ThePlayer and GLOBAL.ThePlayer.HUD
end
local function NullFunction()end

-----------------------积雪--------------------
AddPrefabPostInit("world", function(world)
    local mapfuncs = GLOBAL.getmetatable(world.Map).__index
    local cover = mapfuncs.SetOverlayLerp
    mapfuncs.SetOverlayLerp = function(map, level, ...)
        return cover(map, s_data.snowtile and level or 0, ...)
    end
end)

local function SnowtileFn(show)
    s_data.snowtile = show
end

table.insert(screen_data, 
{
    id = "snowtile",
    label = "地面积雪",
    fn = SnowtileFn,
    hover = "要不要显示地面的积雪？"
})
--------------------水中木-------------------------
local leafcanopy
local function LeafcanopyFn(show)
    local hud = GetHUD()
    local lc_hud = hud.leafcanopy
    if show then
        if type(leafcanopy) == "function" then
            lc_hud.OnUpdate = leafcanopy
        end
        lc_hud:Show()
    else
        lc_hud.OnUpdate = NullFunction
        lc_hud:Hide()
    end
end

AddClassPostConstruct("widgets/leafcanopy", function(self)
    if not s_data.leafcanopy then
        self:Hide()
    end
    leafcanopy = self.OnUpdate
end)

table.insert(screen_data, {
    id = "leafcanopy",
    label = "水中木-巨树华盖",
    fn = LeafcanopyFn,
    hover = "清辉澹水木，\n演漾在窗户。"
})

AddPrefabPostInit("lightrays_canopy", function(inst)
    if not s_data.light_rays then
        inst:Hide()
        inst.AnimState:SetBuild("oceantree_short")
        inst:CancelAllPendingTasks()
        if inst.components.distancefade then
            inst:RemoveComponent("distancefade")
        end
    end
end)
local function LightRaysFn(show)
    local light_rays = e_util:FindEnts(nil, "lightrays_canopy", nil, {"lightrays", "exposure"}, {})
    if show then
        s_data.light_rays = true
        t_util:Pairs(light_rays, function(_,light_ray)
            light_ray:Show()
        end)
    else
        s_data.light_rays = false
        t_util:Pairs(light_rays, function(_, inst)
            inst:Hide()
            inst:CancelAllPendingTasks()
            if inst.components.distancefade then
                inst:RemoveComponent("distancefade")
            end
        end)
    end
end
table.insert(screen_data, {
    id = "light_rays",
    label = "水中木-林间天光",
    fn = LightRaysFn,
    hover = "庭下如积水空明，\n水中藻、荇交横，\n盖竹柏影也。"
})

AddPrefabPostInit("oceanvine_deco", function(inst)
    if not s_data.oceanvine_deco then
        inst:Hide()
    end
end)
local function OceanvineDecoFn(show)
    local decos = e_util:FindEnts(nil, "oceanvine_deco", nil, {"flying"}, {})
    if show then
        t_util:Pairs(decos, function(_, deco) deco:Show() end)
    else
        t_util:Pairs(decos, function(_, deco) deco:Hide() end)
    end
end

table.insert( screen_data, {
    id = "oceanvine_deco",
    label = "水中木-藤蔓装饰",
    fn = OceanvineDecoFn,
    hover = "紫藤挂云木，花蔓宜阳春。\n密叶隐歌鸟，香风留美人。"
})

-------------------光晕和暂停--------------------
local function VigpaintFn(show)
    local anim = GLOBAL.ThePlayer and GLOBAL.ThePlayer.HUD and GLOBAL.ThePlayer.HUD.vig and GLOBAL.ThePlayer.HUD.vig:GetAnimState()
    if anim then
        if show then
            anim:OverrideSymbol("vigpaint", "vig", "vigpaint")
        else
            anim:OverrideSymbol("vigpaint", "hx_trans", "hx_trans")
        end
    end
end

local function SandoverFn(show)
    local hud = GetHUD()
    local dust_loop = hud and hud.sanddustover and hud.sanddustover:GetAnimState()
    local mdust_loop = hud and hud.moonstormdust
    local blind_loop = hud and hud.sandover and hud.sandover.bg and hud.sandover.bg:GetAnimState()
    local mblind_loop = hud and hud.moonstormover and hud.moonstormover.bg and hud.moonstormover.bg:GetAnimState()
    if show then
        if dust_loop then dust_loop:OverrideSymbol("sand_texture2", "sand_over", "sand_texture2") end
        if mdust_loop then mdust_loop:SetSize(1,1) mdust_loop:SetScaleMode(GLOBAL.SCALEMODE_FILLSCREEN) end
        if blind_loop then blind_loop:OverrideSymbol("gradient2", "sand_over", "gradient2")  end
        if mblind_loop then mblind_loop:OverrideSymbol("gradient2", "moonstorm_over", "gradient2") end
    else
        if dust_loop then dust_loop:OverrideSymbol("sand_texture2", "hx_trans", "hx_trans") end
        if mdust_loop then mdust_loop:SetSize(0,0) end          -- 我是真机灵啊
        if blind_loop then blind_loop:OverrideSymbol("gradient2", "hx_trans", "hx_trans")  end
        if mblind_loop then mblind_loop:OverrideSymbol("gradient2", "hx_trans", "hx_trans") end
    end
end

local function PauseFn(show)
    local hud = GetHUD()
    local pausehud = hud.serverpause_underlay
    if pausehud then
        if show then
            pausehud:SetSize(1,1) 
            pausehud:SetScaleMode(GLOBAL.SCALEMODE_FILLSCREEN)
        else
            pausehud:SetSize(0,0)
        end
    end
end
----------------------装备滤镜-------------------
local function HelmFn(show)
    local hud = GetHUD()
    local gogglesover = hud and hud.gogglesover and hud.gogglesover.bg
    local wagover = hud and hud.Wagpunkui and hud.Wagpunkui.overlay and hud.Wagpunkui.overlay:GetAnimState()
    local nutover = hud and hud.nutrientsover and hud.nutrientsover.bg
    if show then
        if gogglesover then gogglesover:SetSize(1,1) gogglesover:SetScaleMode(GLOBAL.SCALEMODE_FILLSCREEN) end
        if nutover then nutover:SetSize(1,1) nutover:SetScaleMode(GLOBAL.SCALEMODE_FILLSCREEN) end
        if wagover then wagover:OverrideSymbol("ui_parts", "wagpunk_over", "ui_parts") end
    else
        if gogglesover then gogglesover:SetSize(0,0) end
        if nutover then nutover:SetSize(0,0) end
        if wagover then wagover:OverrideSymbol("ui_parts", "hx_trans", "hx_trans") end
    end
end

table.insert(screen_data, {
    id = "helmover",
    label = "装备滤镜",
    fn = HelmFn,
    hover = "护目镜、\n耕作先驱帽、\n头戴齿轮\n等装备的景深"
})
AddClassPostConstruct("screens/playerhud", function(self)
	local _CreateOverlays = self.CreateOverlays
	self.CreateOverlays = function(self, ...)
		local result = _CreateOverlays(self, ...)
        VigpaintFn(s_data.overlays)
        SandoverFn(s_data.sandover)
        PauseFn(s_data.pauseover)
        LeafcanopyFn(s_data.leafcanopy)
        HelmFn(s_data.helmover)
        return result
	end
end)

table.insert(screen_data,  {
    id = "overlays",
    label = "屏幕光晕",
    fn = VigpaintFn,
    hover = "屏幕四周有一圈儿\n黑糊糊的滤镜\n或者叫“景深”？ "
})

table.insert(screen_data, {
    id = "sandover",
    label = "沙暴或月亮风暴",
    fn = SandoverFn,
    hover = "沙暴滤镜\n月亮风暴滤镜"
})
table.insert(screen_data, {
    id = "pauseover",
    label = "暂停黑屏",
    fn = PauseFn,
    hover = "这原本是开发者模式的内容\n要不要显示暂停时的屏幕黑屏呢？"
})
--------------------- 伍迪-------------------------
local woodie_show = not s_data.woodieover
local function WoodieFn(show)
    if show ~= GLOBAL.ThePlayer then woodie_show = show end
    local hud = GetHUD()
    local woodie_over = hud and hud.beaverOL
    if not woodie_over then return end
    if woodie_show then
        woodie_over:SetSize(1,1) 
        woodie_over:SetScaleMode(GLOBAL.SCALEMODE_FILLSCREEN)
    else 
        woodie_over:SetSize(0,0)
    end
end

AddPlayerActivatedFunc(function(player, world)
    if not player:HasTag("werehuman") then
        return
    end
    player:ListenForEvent("weremodedirty", WoodieFn)
    WoodieFn()
end)

table.insert(screen_data, {
    id = "woodieover",
    label = "伍迪变身",
    fn = WoodieFn,
    hover = "是否显示伍迪\n变身后的黄色景深？"
})
--------------------------地图----------------------
AddClassPostConstruct("widgets/mapwidget", function(self)
    if s_data.map_bg then
        self.bg:Hide()
    end
end)



table.insert(screen_data, {
    id = "map_bg",
    label = "地图透明",
    fn = function(show)
        s_data.map_bg = show
    end,
    hover = "是否启用地图透明？"
})
----------------------隐藏泰拉瑞亚附近的浆果------------------

local prefab = "terrariumchest"
AddPrefabPostInit(prefab, function(inst)
    inst:DoPeriodicTask(2, function()
        if inst:IsValid() and inst.Transform then
            local pos = inst:GetPosition()
            local fx = pos and GLOBAL.TheSim:FindEntities(pos.x,0,pos.z, 0.1, {"FX"})[1]
            local hide = fx and fx.prefab == prefab.."_fx"
            local bushes = GLOBAL.TheSim:FindEntities(pos.x,0,pos.z, 3, {"bush", "plant"}, {'FX','DECOR','NOCLICK', 'player', 'INLIMBO'})
            for _,bush in pairs(bushes)do
                if hide and not s_data.terr_berry then
                    bush:Hide()
                else
                    bush:Show()
                end
            end
        end
    end)
end)
table.insert(screen_data, {
    id = "terr_berry",
    label = "高亮泰拉瑞亚",
    fn = function(show)
        s_data.terr_berry = show
    end,
    hover = "是否显示泰拉瑞亚箱子附近的浆果丛?"
})
------------------测试-----------------------
-- local F_N = "SetTile"
-- AddPrefabPostInit("world", function(world)
--     local mapfuncs = GLOBAL.getmetatable(world.Map).__index
--     local cover = mapfuncs[F_N]
--     mapfuncs[F_N] = function(map, X,Y,tile,...)
--         local value = cover(map, X,Y,tile,...)
--         -- local value = cover(map, 3, 3)
--         print(map, X,Y,tile,...)
--         return value
--     end
-- end)

-- local function TestFn(show)
-- end

-- table.insert(screen_data, 
-- {
--     id = F_N,
--     label = F_N,
--     fn = TestFn,
--     hover = F_N
-- })
-------------------------加载-------------------
local screen
local function Fn()
    local screen_name = TheFrontEnd:GetActiveScreen().name
    screen_name = TheFrontEnd:GetActiveScreen().name
    if "ScreenScreen" == screen_name then
        TheFrontEnd:PopScreen(screen)
    else
        screen = require("screens/screenscreen")(screen_data)
        TheFrontEnd:PushScreen(screen)
    end
end
if GetModConfigData("sw_beauti") == "biubiu" then
DEAR_BTNS:AddDearBtn(GLOBAL.GetInventoryItemAtlas("butter.tex"), "butter.tex", "画面渲染", "对屏幕遮罩等进行操作", true, Fn)
end
AddBindBtn("sw_beauti", Fn)